#pragma once
#include"UdpSocket.hpp"
#include<functional>
#include<assert.h>

typedef std::function<void (const std::string,std::string* resp)> Handle;

class UdpServer{
    public:
    UdpServer(){
        //创建socket
        assert(_sock.Socket());
    }
    ~UdpServer(){
        _sock.Close();
    }
    void start(u_int16_t port,Handle handle){
        //绑定端口号
        assert(_sock.Bind(port));
        for(;;){
            std::string clientip;
            u_int16_t clientport;
            std::string req;
            bool read=_sock.Recvfrom(&req,&clientip,&clientport);
            if(!read){
                continue;
            }
            std::string resp;
            handle(req,&resp);
            _sock.Sendto(resp,clientip,clientport);
            printf(" [%s %d] req:%s\n resp:%s\n",clientip.c_str(),clientport,req.c_str(),resp.c_str());
        }
        _sock.Close();
        return;
    }
    private:
    UdpSocket _sock;
};
